const express = require("express");
const router = express.Router();
const path = require("path");
const multer = require("multer");
const upload = multer({ dest: path.join(__dirname, "../../../public/images") });

const { timeTrans } = require("../../../utils");
const {
  getBanner,
  addBanner,
  updateBanner,
  deleteBanner,
  showBanner,
} = require("../../../model/weixin/admin/banner");

/* banner增删改查 */

// 查找banner
router.get("/", async function (req, res, next) {
  let data = await getBanner();
  res.send(data);
});

// 添加banner
router.post("/add", upload.single("banner"), (req, res, next) => {
  const banner_id = Number(req.body.banner_id);
  const src = "http://localhost:3333/images/" + req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  addBanner([banner_id, src, atime])
    .then(() => {
      res.send({
        code: 200,
        msg: "添加轮播图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "添加轮播图片失败",
        err,
      });
    });
});

// 修改banner
router.post("/update", (req, res, next) => {
  console.log(req.body);
  const banner_id = Number(req.body.banner_id);
  const src =
    "http://localhost:3333/images/" + req.body["src[name]"] ||
    req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  updateBanner([src, atime, banner_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改轮播图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改轮播图片失败",
        err,
      });
    });
});

// 删除单个banner
router.get("/delete", (req, res, next) => {
  // console.log(req.query);
  const banner_id = Number(req.query.banner_id);
  deleteBanner([banner_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除图片失败",
      });
    });
});

// 是否展示banner
router.get("/show", (req, res, next) => {
  // console.log(req.query);
  const isShow = req.query.isShow === "false" ? false : true;
  const banner_id = Number(req.query.banner_id);

  showBanner([isShow, banner_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改图片失败",
      });
    });
});

module.exports = router;
